﻿
using Identitymodels;
using Identitymodels.Authorization;
using Infra_common.Aes;
using Infra_common.Md5;
using Infra_common.YIBanUrl;
using log4net;
using MediatR;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using xiaodingmarket_application.Interfaces;
using xiaodingmarket_application.ViewModel;
using xiaodingmarket_Domain.Interfaces.IRepository;
using xiaodingmarket_Domain.Models;
using xiaodingmarket_Domain_core.Bus;
using xiaodingmarket_Domain_core.Notificatiions;
using xiaodingmarket_service.Cache;
using xiaodingmarket_service.Configurations;
using static Infra_common.Aes.AesModel;

namespace xiaodingmarket_service.Controllers
{
    [Route("api/[controller]")]
    //[ApiController]
    public class AccountController : ApiController
    {

        //专门用来用户认证和签发token的控制器（—框架自带）修改为使用我们自己的仓储
        //private readonly SignInManager<IdentityUser> _signInManager;
        //private readonly UserManager<IdentityUser> _userManager;
        //private readonly TokenManagement _appSettings;
        private readonly YBUrl _yburl;
        private readonly Aes aes;
        private readonly IUserService _Userservice;
        private readonly IRoleService _Roleservice;
        private readonly IConfiguration _configuration;
        private readonly JwtToken _jwttoken;
        private readonly IUserRepository _UserRepository;
        private readonly IUserRoleRepository _UserroleRepository;
        public AccountController(
            IUserService userservice,
            IRoleService roleservice,
            //SignInManager<IdentityUser> signInManager,
            //UserManager<IdentityUser> userManager,
            YBUrl yburl,
            //IOptions<TokenManagement> appSettings,
            INotificationHandler<DomainNotification> notifications,
            IMediatorHandler mediator,
            IConfiguration configuration,
            JwtToken jwttoken ,
            IUserRepository UserRepository,
            IUserRoleRepository UserroleRepository,
            Aes A) : base(notifications, mediator)
        {
            //_userManager = userManager;
            //_signInManager = signInManager;
            //_appSettings = appSettings.Value;
            aes = A;
            _UserRepository = UserRepository;
            _Userservice = userservice;
            _Roleservice = roleservice;
            _yburl = yburl;
            _configuration = configuration;
            _jwttoken = jwttoken;
            _UserroleRepository = UserroleRepository;
        }

        //[HttpPost]
        //[Route("register")]
        //public async Task<IActionResult> Register(UserRegistration userRegistration)
        //{
        //    if (!ModelState.IsValid)
        //    {
        //        NotifyModelStateErrors();
        //        return Response(userRegistration);
        //    }
        //    var user = new IdentityUser
        //    {
        //        UserName = userRegistration.Email,
        //        Email = userRegistration.Email,
        //        EmailConfirmed = true
        //    };
        //    Log4netHelper.Debug("111111");
        //    var result = await _userManager.CreateAsync(user, userRegistration.Password);

        //    if (!result.Succeeded)
        //    {
        //        foreach (var error in result.Errors)
        //        {
        //            NotifyError(error.Code, error.Description);
        //        }

        //        return Response(userRegistration);
        //    }

        //    await _signInManager.SignInAsync(user, false);
        //    var token = await GenerateJwt(userRegistration.Email);

        //    return Response(token);
        //}

        /// <summary>
        /// 易班嵌套登录注册都在这一个接口，code是授权则返回jwt
        /// </summary>
        /// <param name="userLogin"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("YBlogin")]
        public async Task<IActionResult> YBLogin(UserYBLogin userLogin)
        {
            //检验model中属性的特性设置是否满足
            if (!ModelState.IsValid)
            {
                NotifyModelStateErrors();
                return Response(userLogin);
            }
            //原Microsoft.AspNetCore.Identity配置登录功能
            //var result = await _signInManager.PasswordSignInAsync(userLogin.Email, userLogin.Password, false, true);
            //if (result.Succeeded)
            //{
            //    var token = await GenerateJwt(userLogin.Email);
            //    return Response(token);
            //}
           

            
            try
            {
                //解密
                aesmodel re = aes.GetToken(userLogin.Code);
                if (re.visit_oauth.access_token == null)
                {
                    NotifyError("Login", "未授权或者token已过期");
                }
                else
                {
                    //判断是否已经注册过（先用数据库，以后可以改成redis提高性能）
                    if (_Userservice.hasCreate(re.visit_user.userid))
                    {
                        var user = _Userservice.GetBystudentId(re.visit_user.userid);
                        string userrole = "";
                        //登陆（先通过用户角色表获取到角色,5F668E64-8956-BA8E-67EA-503D01089EB1-普通，2AA4CB5E-66BA-9139-6F77-3BAA108375AB-管理，CFB8903E-7C41-ABBC-66F2-9368D0DF4268-超级管理）
                        //懒得写ef查询role了，直接判断一下吧
                        foreach(var role in user.userroles)
                        {
                            if (role.RoleID.ToString().Equals("CFB8903E-7C41-ABBC-66F2-9368D0DF4268"))
                            {
                                userrole = "SuperAdmin";
                                break;
                            }
                            else if (role.RoleID.ToString().Equals("2AA4CB5E-66BA-9139-6F77-3BAA108375AB") && !userrole.Equals("SuperAdmin"))
                            {
                                userrole = "Admin";
                            }
                            else if ((role.RoleID.ToString().Equals("5F668E64-8956-BA8E-67EA-503D01089EB1") && userrole.Equals("")))
                            {
                                userrole = "OrdUser";
                            }
                        }
                        
                        var token = await _jwttoken.GetJwtToken(re.visit_user.username,re.visit_user.userid, true, userrole, _configuration);
                        return Response(token);
                    }
                    else
                    {
                        
                        string responseContent = _yburl.Getapi("https://openapi.yiban.cn/user/verify_me?access_token=" + re.visit_oauth.access_token);
                        string responseContent1 = _yburl.Getapi("https://openapi.yiban.cn/user/real_me?access_token=" + re.visit_oauth.access_token);
                        //var response = new { statu = "", info = "" };
                        //var Result1 = JsonConvert.DeserializeAnonymousType(responseContent, response);
                        JObject Result = JObject.Parse(responseContent);
                        JObject Result1 = JObject.Parse(responseContent1);
                        if (Result["status"].ToString().Equals("success")&& Result1["status"].ToString().Equals("success")) //成功返回
                        {
                            var token =await _jwttoken.GetJwtToken(Result1["info"]["yb_usernick"].ToString(),Result["info"]["yb_userid"].ToString(),false, "OrdUser", _configuration);
                            _Userservice.Create(new UserViewModel(Result["info"]["yb_studentid"].ToString(), Result["info"]["yb_realname"].ToString(), Result1["info"]["yb_sex"].ToString(), Result["info"]["yb_collegename"].ToString(), Result1["info"]["yb_userid"].ToString(), Result1["info"]["yb_usernick"].ToString(), Result1["info"]["yb_userhead"].ToString()));
                            return Response(token);
                        }
                        else
                        {
                            NotifyError("Login", "无法获取用户易班认证信息");
                        }
                    }
                    
                }
            }
            catch (Exception e)
            {
                NotifyError("Login", e.Message);
            }


            return Response(userLogin);
        }
        /// <summary>
        /// 普通学号密码登陆，role有游客，普通用户，管理员，超级管理员
        /// </summary>
        /// <param name="userLogin"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("login")]
        public async Task<IActionResult> Login(UserLogin userLogin)
        {
            if (!ModelState.IsValid)
            {
                NotifyModelStateErrors();
                return Response(userLogin);
            }
            try
            {
                var user = _Userservice.GetallBystudentId(userLogin.StudentId);
                if (user == null) return Response("用户不存在！");
                var code = MD5Encrypt.Encrypt32(userLogin.Password);
                //判断用户名密码是否相同
                if (user.Pwd.Equals(code))
                {
                    var token="";
                    bool b= false;
                    //判断角色是否一致
                    foreach (var item in user.userroles)
                    {
                        //_Roleservice.GetRoleinfo(item.RoleID);
                        if (item.Role.Name.Equals(userLogin.role))
                        {
                            b = true;
                            token = await _jwttoken.GetJwtToken(user.StudentName, user.StudentId, true, userLogin.role, _configuration);
                            break;
                        }
                    }
                    if (b)
                    {
                        return Response(token);
                    }
                    else
                    {
                        return Response("角色权限选择错误");
                    }
                }
                else
                {
                    return Response("密码不正确");
                }
            }
            catch(Exception ex)
            {
                return Response(ex.Message);
            }

            
        }

        /// <summary>
        /// 普通账号密码注册，其他个人信息可以再后面我的页面进行编辑
        /// </summary>
        /// <param name="userLogin"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("register")]
        public async Task<IActionResult> Register(UserRegistration userreg)
        {
            if (!ModelState.IsValid)
            {
                NotifyModelStateErrors();
                return Response(userreg);
            }
            try
            {
                if (_Userservice.hasCreate(userreg.StudentId))
                {
                    return Response("该学号已经注册过了");
                }
                else
                {
                    //这里后续可以添加一个检验学号是否为真的功能10F88321-2B28-4324-8B21-87BC7A0FD1C8

                    //仅有学号密码信息是游客权限
                    Guid id = Guid.NewGuid();
                    var token = await _jwttoken.GetJwtToken("游客", userreg.StudentId, false, "Visitor", _configuration);
                    

                    var user = new User(id, userreg.StudentId, "游客", MD5Encrypt.Encrypt32(userreg.Password), DateTime.Now, DateTime.Now, DateTime.Now, userreg.StudentId, userreg.StudentId, false);
                    _UserRepository.Add(user);
                    _UserRepository.SaveChanges();
                    var Role=_Roleservice.GetRoleinfo (new Guid("5f778e64-8956-ba8e-67ea-503d01089eb1"));
                    var userrole=new UserRoles(id, new Guid("5F008E64-8956-BA8E-67EA-503D01089EB1"), user, Role, false);

                    _UserroleRepository.Add(userrole);
                    _UserroleRepository.SaveChanges();

                    return Response(token);
                }
            }
            catch(Exception e)
            {
                return Response("注册失败");
            }
            
        }












        //原获取token的方法
        //private async Task<string> GenerateJwt(string email)
        //{
        //    var user = await _userManager.FindByEmailAsync(email);
        //    var claims = await _userManager.GetClaimsAsync(user);

        //    claims.Add(new Claim(JwtRegisteredClaimNames.Sub, user.Id));
        //    claims.Add(new Claim(JwtRegisteredClaimNames.Email, user.Email));

        //    var identityClaims = new ClaimsIdentity();
        //    identityClaims.AddClaims(claims);

        //    var tokenHandler = new JwtSecurityTokenHandler();
        //    var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
        //    var tokenDescriptor = new SecurityTokenDescriptor
        //    {
        //        Subject = identityClaims,
        //        Issuer = _appSettings.Issuer,
        //        Audience = _appSettings.ValidAt,
        //        Expires = DateTime.UtcNow.AddHours(_appSettings.Expiration),
        //        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
        //    };

        //    return tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor));
        //}

        //现获取token的方法
        //iss ： jwt签发者   sub：jwt所面向的用户    aud：接收jwt的一方




    }
}
//{
//  "email": "11111111@qq.com",
//  "password": "123456!Aa",
//  "passwordConfirm": "123456!Aa"
//}
//下面是上面这个账号的jwt，可以直接用
//eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI3Mzc3OGU1ZS04NmFlLTQ2MGYtYTBmYS1lYWEyNzIxMjQzYmQiLCJlbWFpbCI6IjExMTExMTExQHFxLmNvbSIsIm5iZiI6MTU4MzkyNTE0MSwiZXhwIjoxNTgzOTYxMTQxLCJpYXQiOjE1ODM5MjUxNDEsImlzcyI6Ik15RW52aXJvbm1lbnQiLCJhdWQiOiJodHRwczovL2xvY2FsaG9zdCJ9.ryx557SHMNv2_8L3451pR1GavcDvLdk7S7k8QYobqmI